package com.android.semita;

import java.text.DecimalFormat;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.semita.controller.InvoiceController;
import com.android.semita.model.Invoice;

import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class InvoiceDetailActivity extends Activity {
	
	public static final String INVOICE_NO="InvoiceNo";
	public static final String TARGETDATE="TargetDate";
	public static final String ADDRESS = "Address";
	public static final String ADDRESSGPS="AddressGPS";
	public static final String INVOICESTATUS="InvoiceStatus";
	public static final String CUSTOMERNAME="CustomerName";
	public static final String LATITUDE ="latitude";
	public static final String LONGTITUDE ="longtitude";
	protected static final int ACTIVITY_SHOW_MAP = 2;
	
	
	private static String APIUrl ="http://202.21.149.53/SemitaServices/api/";
	
	
	private InvoiceItemAdapter adapterInvoiceItemList;
	private ListView lvInvoiceItemList;

	private TextView tvTotalInvoiceItem;
	private TextView tvTotalInvoiceItemAmount;

	private TextView tvInvoiceNo;
	private TextView tvCustomerID;
	private TextView tvCustomerAddress;
	
	private String InvoiceNo = "";
	

	//private ArrayList<InvoiceItem> invoice_detail_list;
	private Invoice currentInvoice = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_invoice_detail);
		// Show the Up button in the action bar.
		setupActionBar();

		lvInvoiceItemList = (ListView) findViewById(R.id.lvInvoiceItemList);

		tvInvoiceNo = (TextView) findViewById(R.id.txtInvoiceNo);
		tvCustomerID = (TextView) findViewById(R.id.txtCustomerID);
		tvCustomerAddress = (TextView) findViewById(R.id.txtCustomerAddress);

		InvoiceNo = getIntent().getStringExtra("InvoiceNo"); //"SI-131100001";
		//MessengerId = getIntent().getStringExtra("MessengerId"); //"1";
		
		//call AsyncTask for get JSON string
		new getJSONInvoiceItems(this).execute(InvoiceNo);
		

	}

	private void Summary(Float totalAmount) {
		Integer countInvoiceItem = currentInvoice.getInvoiceItems().size();

		tvTotalInvoiceItem = (TextView) findViewById(R.id.textview_count_invoice_item);
		tvTotalInvoiceItemAmount = (TextView) findViewById(R.id.textview_total_invoice_amount);
		
		if (tvTotalInvoiceItem != null) {
			tvTotalInvoiceItem.setText(countInvoiceItem.toString());
		}
		if (tvTotalInvoiceItemAmount != null) {
			tvTotalInvoiceItemAmount.setText(totalAmount.toString());
		}
	}

	//call back method for AsyncTask::getJSONInvoiceDetail()
	private void GetInvoiceItemsFromJSON(String JSONString, ProgressDialog dialog)
	{
		try
		{	
			String jsonString= JSONString.substring(1, JSONString.length() - 1);
			currentInvoice = new InvoiceController().getInvoiceFromJSON(jsonString);
			
			tvInvoiceNo.setText(currentInvoice.getInvoiceNo());
			tvCustomerID.setText("(" + currentInvoice.getCustomerId() + ")" + currentInvoice.getCustomerName());
			tvCustomerAddress.setText(currentInvoice.getCustomerAddress());			
			
			adapterInvoiceItemList = new InvoiceItemAdapter(this,R.layout.invoice_item_list, currentInvoice.Items);
			lvInvoiceItemList.setAdapter(adapterInvoiceItemList);

			Summary(currentInvoice.getInvoiceAmount());
		}
		finally
		{
			if (dialog.isShowing()) {
                dialog.dismiss();
            }
		}
	}
	
	
	/////////////////////////////////////////////////////////////////////////////
	private class getJSONInvoiceItems extends AsyncTask<String, Integer, String> 
	{
		private Context context;
		private ProgressDialog dialog;
		
		public getJSONInvoiceItems(InvoiceDetailActivity activity) {
            context = activity;
            dialog = new ProgressDialog(context);
            dialog.setCancelable(true);
        }
		
		@Override
		protected void onPreExecute() {
			this.dialog.setMessage("Waiting...");
            this.dialog.show();
		}
		
		@Override
		protected String doInBackground(String... InvoiceNo) 
		{
			String returnJSONString = "";
			String invoiceNo = InvoiceNo[0];			
			String RequestURL = APIUrl + "InvoiceDetail?invoice_no=" + invoiceNo;

			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);
				
				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
			e.printStackTrace();
			}
		
			return returnJSONString;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
		}
		
		@Override
		protected void onPostExecute(String JSONResult) 
		{
			GetInvoiceItemsFromJSON(JSONResult, dialog);
		}
	}
	/////////////////////////////////////////////////////////////////////////////
	
	private void ratingActionResult(boolean RateSuccess, ProgressDialog dialog)
	{
		dialog.dismiss();
		
		String dialogMessage="";
		
		if(RateSuccess){
			dialogMessage = "Thank you for feedback.";
		}
		else{
			dialogMessage = "Update feedback not success.";
		}
		
		new AlertDialog.Builder(this)
        .setMessage(dialogMessage)
        .setCancelable(false)
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                 finish();
            }
        })
        .show();
		
	}
	/////////////////////////////////////////////////////////////////////////////
	private class ratingAndConfirmShipped extends AsyncTask<String, Integer, String> 
	{
		private Context context;
		private ProgressDialog dialog;
		
		public ratingAndConfirmShipped(InvoiceDetailActivity activity) {
			context = activity;
			dialog = new ProgressDialog(context);
			dialog.setCancelable(true);
		}
		
		@Override
		protected void onPreExecute() {
			this.dialog.setMessage("Waiting...");
			this.dialog.show();
		}
		
		@Override
		protected String doInBackground(String... values) 
		{
			String returnJSONString = "";			
			String feedbackScore =  values[0];
						
			
	    	String RequestURL = APIUrl +  "CustomerRating?invoice_no=" + InvoiceNo + "&feedback_score=" + feedbackScore;
			
			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);
				
				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
			e.printStackTrace();
		}
		
		return returnJSONString;
		}
		

		@Override
		protected void onProgressUpdate(Integer... values) {}
		
		@Override
		protected void onPostExecute(String JSONResult) 
		{
			//replace double quote 
			JSONResult = JSONResult.replace("\"", "");
						
			if(JSONResult.equalsIgnoreCase("true"))
			{
				ratingActionResult(true, dialog);
			}
			else
			{
				ratingActionResult(false, dialog);
			}
			
		}
	}
	/////////////////////////////////////////////////////////////////////////////

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.invoice_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_rating:
			//Intent intent = new Intent(this, FeedBackActivity.class);
			//startActivityForResult(intent, 0);
			ShowRatingDialog();
			break;
		case R.id.action_show_map:
			new getJSONMessengerLocation().execute("");
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}

	public void ShowRatingDialog()
	{
		final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
		final RatingBar rating = new RatingBar(this);
		rating.setMax(5);
		rating.setNumStars(5);
		rating.setStepSize(1f);
		rating.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		LinearLayout parent = new LinearLayout(InvoiceDetailActivity.this);
		
		parent.setGravity(Gravity.CENTER);
		parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		parent.addView(rating);

		popDialog.setIcon(android.R.drawable.btn_star_big_on);
		popDialog.setTitle("Rating Our Service. ");
		popDialog.setView(parent);

		// Button OK
		popDialog.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String score = String.valueOf(rating.getProgress());						
						
						UpdateFeedbackScoreAndUpdateStatus(score);
						dialog.dismiss();
					}
				})

		// Button Cancel
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		popDialog.create();
		popDialog.show();

	}
	
	/////////////////////////////////////////////////////////////////////////////
	private void showMapFromMessengerLocation(String JSONString)
	{
		
		try {
			JSONObject invoiceJSONObject;
			invoiceJSONObject = new JSONObject(JSONString);
			
			JSONArray invoiceArray = invoiceJSONObject.getJSONArray("MessengerLocation");			
			
			JSONObject locationItemObject = invoiceArray.getJSONObject(0);
			
			Double latitute = Double.parseDouble(locationItemObject.getString("LastUpdateLocation").split(",")[0]);
			Double longtitute = Double.parseDouble(locationItemObject.getString("LastUpdateLocation").split(",")[1]);
			
			if (latitute != null && longtitute != null) {
				Intent intent_show_map = new Intent(this, LocationMapActivity.class);
				intent_show_map.putExtra(LATITUDE,latitute);
				intent_show_map.putExtra(LONGTITUDE,longtitute);
				intent_show_map.putExtra(ADDRESS,"");
				intent_show_map.putExtra(CUSTOMERNAME,"");
				intent_show_map.putExtra(INVOICE_NO,InvoiceNo);
				
				
				startActivityForResult(intent_show_map, ACTIVITY_SHOW_MAP);
			} else {
				alert("GPS location not found");
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}
	/////////////////////////////////////////////////////////////////////////////
	
	private void alert(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}
	
	private class getJSONMessengerLocation extends AsyncTask<String, Integer, String> 
	{
		
		@Override
		protected void onPreExecute() {			
		}

		@Override
		protected String doInBackground(String... values) 
		{
			String returnJSONString = "";			
			String RequestURL = APIUrl +  "messengerLocation?invoice_no=" + InvoiceNo;

			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);

				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}


		@Override
		protected void onProgressUpdate(Integer... values) {}

		@Override
		protected void onPostExecute(String JSONResult) 
		{
			//replace double quote 
			JSONResult= JSONResult.substring(1, JSONResult.length() - 1);
			
			showMapFromMessengerLocation(JSONResult);

		}
	}
	/////////////////////////////////////////////////////////////////////////////


	private void UpdateFeedbackScoreAndUpdateStatus(String Score)
	{
		String location = getLocationString();
		
		//call asyncTask for update status and rating
		new ratingAndConfirmShipped(this).execute(Score,location);
	}
	
	private String getLocationString()
	{
		DecimalFormat decimalFormat = new DecimalFormat("#.00000");
    	
    	Location location = getCurrentLocation();
    	String locationString = "";
    	
    	if(location != null)
    	{
    		locationString = decimalFormat.format(location.getLatitude()) + "," + decimalFormat.format(location.getLongitude());
    	}

    	return locationString;
	}
	
    private Location getCurrentLocation() {
    	LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	List<String> providers = manager.getAllProviders();
    	for(String provider: providers)
    		if(manager.isProviderEnabled(provider)) {
    			Location loc = manager.getLastKnownLocation(provider);
    			return loc;
    		}
    	
    	return null;
    }
}
